//
//  CZComposeViewController.swift
//  weibo
//
//  Created by 丁蒙 on 16/7/3.
//  Copyright © 2016年 丁蒙. All rights reserved.
//

import UIKit

class CZComposeViewController: UIViewController {
    //间距
    let Margin: CGFloat = 5
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
    }
    // MARK: - 跳转相册
    func selectImage() {
        let pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        presentViewController(pickerVC, animated: true, completion: nil)
        
    }
    
    // MARK: - 设置视图
    private func setupUI() {
        setupNav()
        //添加子控件
        view.addSubview(textV)
        view.addSubview(composeToolbar)
        textV.addSubview(composeView)
        
        //设置约束
        textV.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composeToolbar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        composeView.snp_makeConstraints { (make) in
            make.top.equalTo(textV).offset(100)
            make.left.equalTo(textV).offset(10)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }
        //监听点击cell的闭包
        composeView.composeViewClosure = {[weak self] in
            self?.selectImage()
        }
        
        // MARK: - 使用系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComposeViewController.keyboardDidChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        // MARK: - 接收表情按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComposeViewController.emoticonButtonClick(_:)), name: EmoticonButtonNoti, object: nil)
        // MARK: - 接收回退按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComposeViewController.backButtonClick), name: BackButtonNoti, object: nil)
        
        // MARK: - 监听composeToolbar按钮点击
        composeToolbar.closure = {[weak self] (type: CZComposeToolbarType) in
            
            switch type {
            case .Picture:
                self?.composeView.hidden = false
                self?.selectImage()
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                self?.switchKeyboard()
            case .Add:
                print("Add")
            
            }
        }
    }
    // MARK: - 监听回退按
    func backButtonClick() {
        textV.deleteBackward()
    }
    // MARK: - 监听表情键盘
    func emoticonButtonClick(noti: NSNotification) {
        guard let emocitons = noti.object as? CZEmoticons else {
            return
        }
        
        if emocitons.isEmoji {
            textV.insertText(((emocitons.code ?? "") as NSString).emoji())
        } else {
            
            let oldAttr = NSMutableAttributedString(attributedString: textV.attributedText)
            
            let att = CZTextAttachment()
            att.emoticon = emocitons
            
            let png = emocitons.png ?? ""
            let path = emocitons.path ?? ""
            let name = path + png
            
            att.image = UIImage(named: name, inBundle: CZEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            let lineHight = textV.font!.lineHeight
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHight, height: lineHight)
            
            let attr = NSAttributedString(attachment: att)
            
            let selectedRange = textV.selectedRange
            
            
            oldAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            
            oldAttr.addAttributes([NSFontAttributeName:textV.font!], range: NSRange(location: 0, length: oldAttr.length))
            
            textV.attributedText = oldAttr
            
            textV.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            
            // 发送一个系统通知 隐藏或者显示textView 的站位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            // 调用代理方法使右侧按钮改变状态
            textV.delegate?.textViewDidChange!(textV)
            
            
        }
    }
    // MARK: - 切换键盘
    func switchKeyboard() {
        if textV.inputView == nil {
            textV.inputView = keyBoardView
            composeToolbar.isEmotion = true
        }else{
            textV.inputView = nil
            composeToolbar.isEmotion = false
        }
        textV.reloadInputViews()
        textV.becomeFirstResponder()
    }
    // MARK: - 监听键盘的方法 改变frame
    func keyboardDidChangeFrame(noti: NSNotification) {
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
            composeToolbar.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
                
                //添加动画
                UIView.animateWithDuration(0.25, animations: {
                    //更新约束
                    self.view.layoutIfNeeded()
                })
        }
    }
    // MARK: - 设置nav
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZComposeViewController.cancel))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZComposeViewController.send))
        //发送按钮默认不能被点击
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    // MARK: - 按钮点击事件
    @objc private func cancel() {
        textV.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    @objc private func send() {
        
        var resultStr = ""
        
        textV.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: textV.attributedText.length), options: []) { (dict, range, _) -> Void in
            
            // 如果是文本附件
            if let att = dict["NSAttachment"] as? CZTextAttachment {
                resultStr += (att.emoticon?.chs ?? "")
            }else {
                // 文字
                let name = (self.textV.attributedText.string as NSString).substringWithRange(range)
                resultStr += name

            }
        }
        // 如果配图中的数组.count > 0 代表发送有图片微博
        if composeView.imageList.count > 0{
            upload(resultStr)
        }else{
            // 发送文字微博
            update(resultStr)
        }

    }
    // MARK: - 发布微博方法
    //文字文博
    func update(status: String) {
        CZNetWorkTools.sharedTools.updateWeibo(status, success: { (response) in
            print("发送成功")
            }) { (error) in
                print("发送失败\(error)")
        }
    }
    //带图片微博
    func upload(status: String) {
        CZNetWorkTools.sharedTools.uploadWeibo(status, imageList: composeView.imageList, success: { (response) in
            print("发送成功")
            }) { (error) in
                print("发送失败\(error)")
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
       let tit = UILabel()
        
        let name = CZUserAccountTools.sharedUserAccountTools.userAccount?.screen_name ?? ""
        let str = "发微博\n\(name)"
        
        let arr = NSMutableAttributedString(string: str)
        
        let range = (str as NSString).rangeOfString(name)
        
        arr.addAttributes([NSForegroundColorAttributeName: ThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
        
        tit.textAlignment = .Center
        tit.numberOfLines = 0
        
        tit.attributedText = arr
        
        tit.sizeToFit()
        return tit
    }()
    
    // MARK: - textView
    private lazy var textV:CZComposeTextView = {
    
        let tex = CZComposeTextView()
        tex.placeholder = "发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博发布微博"
        tex.font = UIFont.systemFontOfSize(16)
        tex.delegate = self
        //可以滚动
        tex.alwaysBounceVertical = true
        return tex
    
    }()
    // MARK: - 底部toolbar
    private lazy var composeToolbar: CZComposeToolbar = CZComposeToolbar()
    // MARK: - 图片视图
    private lazy var composeView: CZComposeView = {
       let view = CZComposeView()
        view.hidden = true
        return view
    }()
    // MARK: - 自定义表情键盘
    private  lazy var keyBoardView:CZKeyboardView = {
        let view = CZKeyboardView()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        return view
    }()
    
    // MARK: - 压缩图片调用的方法
    func scaleImage(width: CGFloat,image: UIImage) -> UIImage {
        
        if width > image.size.width {
            return image
        }
        let imageHeight = (width * image.size.height) / image.size.height
        
        let rect = CGRect(x: 0, y: 0, width: width, height: imageHeight)
        
        //开启上下文
        UIGraphicsBeginImageContext(rect.size)
        //渲染
        image.drawInRect(rect)
        
        let getImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return getImage
    }
}
// MARK: - UITextViewDelegate
extension CZComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textV.resignFirstResponder()
    }
}

// MARK: - UIImagePickerControllerDelegate
extension CZComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //给图片数组赋值
        composeView.addImage(scaleImage(600, image: image))
        
        picker.dismissViewControllerAnimated(false, completion: nil)
    }
    
}







